<template>
  <div>
    <search-pane
      :show="showSearchPane"
      @search="handleSearchLaboratory"
      @reset="resetLaboratoryQueryParams"
    >
      <search-item>
        <PDInput
          v-model="queryParams.labId"
          input-width="200px"
          description="实验室编号"
        />
      </search-item>
      <search-item>
        <PDInput
          v-model="queryParams.name"
          input-width="200px"
          description="实验室名称"
        />
      </search-item>
      <search-item
        label="单位名称"
      >
        <el-select
          v-model="queryParams.unitId"
          size="mini"
          clearable
          @clear="handleClear('unitId')"
        >
          <el-option
            v-for="item in unitList"
            :key="item.unitId"
            :label="item.name"
            :value="item.unitId"
          />
        </el-select>
      </search-item>
      <search-item v-if="false" label="开放时间">
        <el-time-picker
          v-model="currentQueryTime"
          size="mini"
          value-format="HH:mm:ss"
          format="HH:mm"
          placeholder="选择时间"
          is-range
        />
      </search-item>
    </search-pane>

    <table-tool-bar
      v-model="showSearchPane"
      @handleCreate="handleCreateLaboratory"
      @refresh="fetchLaboratoryPage"
    />

    <table-card>
      <el-table
        ref="filterTable"
        :data="laboratoryList"
        style="width: 100%"
      >
        <el-table-column
          prop="labId"
          label="实验室编号"
        />
        <el-table-column
          prop="name"
          label="实验室名称"
        />
        <el-table-column
          prop="unitName"
          label="所属单位"
        />
        <el-table-column
          prop="openTime"
          label="开放时间"
        >
          <template slot-scope="scope">
            <div v-for="item in scope.row.openingSchedule" :key="item.id">
              {{ item.startTime }} - {{ item.endTime }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          width="200"
        >
          <template slot-scope="scope">
            <table-option-group
              type="button"
              @handleDelete="handleDeleteLaboratory(scope.row.labId)"
              @handleUpdate="handleUpdateLaboratory(scope.row)"
            />
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="fetchLaboratoryPage"
      />
    </table-card>

    <form-dialog
      v-model="dialogFormVisible"
      :type="formType"
      @create="createLaboratory"
      @update="updateLaboratory"
    >
      <el-form
        ref="laboratoryForm"
        :rules="formRules"
        :model="tempLaboratory"
      >
        <el-form-item prop="labId" label="实验室编号">
          <el-input v-model="tempLaboratory.labId" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="name" label="实验室名称">
          <el-input v-model="tempLaboratory.name" style="width: 300px" />
        </el-form-item>

        <el-form-item prop="openingSchedule" label="开放时间">
          <div v-for="(item,index) in tempLaboratory.openingSchedule" class="muti-time-picker">
            <el-time-picker
              v-model="currentFormTime[index]"
              size="mini"
              value-format="HH:mm:ss"
              format="HH:mm"
              placeholder="选择时间"
              is-range
            />
          </div>

        </el-form-item>

        <el-form-item prop="unitId" label="单位">
          <el-select
            v-model="tempLaboratory.unitId"
            size="small"
            class="unit-selector"
            clearable
            filterable
            placeholder="单位名称"
          >
            <el-option
              v-for="item in unitList"
              :key="item.name"
              :label="item.name"
              :value="item.unitId"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </form-dialog>
  </div>
</template>

<script>
import SearchPane from '@/components/SearchPane/SearchPane'
import SearchItem from '@/components/SearchPane/SearchItem'
import PDInput from '@/components/SearchPane/PDInput'
import TableCard from '@/components/table/TableCard'
import TableToolBar from '@/components/table/TableToolBar'
import { addLaboratory, deleteLaboratory, pageLaboratories, updateLaboratory } from '@/api/laboratory'
import FormDialog from '@/components/FormDialog/FormDialog'
import TableOptionGroup from '@/components/table/TableOptionGroup'
import { showSuccessTip } from '@/utils/simple-tips'
import Pagination from '@/components/Pagination'
import { listUnits } from '@/api/unit'

export default {
  name: 'Laboratory',
  components: { Pagination, TableOptionGroup, FormDialog, TableToolBar, TableCard, PDInput, SearchItem, SearchPane },
  data() {
    return {
      // search attr
      showSearchPane: true,
      queryParams: {
        pageSize: 5,
        pageNum: 1
      },
      total: 10,

      // form attr
      tempLaboratory: {

      },
      dialogFormVisible: false,
      formType: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      formRules: {

      },

      // table attr
      laboratoryList: [],

      // common attr
      endTimePickerRange: '',
      currentQueryTime: ['08:00:00', '18:00:00'],
      currentFormTime: [],
      unitList: []
    }
  },
  watch: {
    currentQueryTime(newValue, oldValue) {
      console.log(newValue, oldValue)
      if (newValue === null) {
        console.log('null')
        this.queryParams.startTime = undefined
        this.queryParams.endTime = undefined
      }
      this.queryParams.startTime = newValue[0]
      this.queryParams.endTime = newValue[1]
    },
    currentFormTime: {
      handler(newValue, oldValue) {
        console.log(newValue, oldValue)
        for (let i = 0; i < newValue.length; i++) {
          const tempOpeningHour = this.tempLaboratory.openingSchedule[i]
          tempOpeningHour.startTime = newValue[i][0]
          tempOpeningHour.endTime = newValue[i][1]
        }
      },
      deep: true
    }
  },
  mounted() {
    this.fetchLaboratoryPage()
    this.fetchUnitList()
  },
  methods: {
    // region common function
    handleTimePicker(startTime) {
      this.endTimePickerRange = startTime + ' - 23:59:00'
    },

    // endregion

    fetchLaboratoryPage() {
      pageLaboratories(this.queryParams).then(response => {
        this.laboratoryList = response.data.list
        this.total = response.data.total
      })
    },
    fetchUnitList() {
      listUnits().then(response => {
        this.unitList = response.data
      })
    },

    // region search relative function
    handleSearchLaboratory() {
      this.fetchLaboratoryPage()
    },
    resetLaboratoryQueryParams() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5
      }
    },
    handleClear(param) {
      this.queryParams[param] = undefined
    },
    // endregion

    // region form relative function
    resetTempLaboratory() {
      this.tempLaboratory = {
        openingSchedule: []
      }
    },
    handleCreateLaboratory() {
      this.resetTempLaboratory()
      this.tempLaboratory.openingSchedule.push({
        labId: '',
        startTime: '08:00:00',
        endTime: '18:00:00'
      })
      this.currentFormTime = []
      const time = ['08:00:00', '18:00:00']
      this.currentFormTime.push(time)
      this.formType = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['laboratoryForm'].clearValidate()
      })
    },
    createLaboratory() {
      this.$refs['laboratoryForm'].validate((valid) => {
        if (valid) {
          addLaboratory(this.tempLaboratory).then(() => {
            this.fetchLaboratoryPage()
            this.dialogFormVisible = false
            showSuccessTip()
          })
        }
      })
    },
    handleUpdateLaboratory(row) {
      console.log(JSON.stringify(row))
      this.tempLaboratory = Object.assign({}, row)
      this.currentFormTime = []
      row.openingSchedule.forEach(item => {
        const time = [item.startTime, item.endTime]
        this.currentFormTime.push(time)
      })
      this.formType = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['laboratoryForm'].clearValidate()
      })
    },
    updateLaboratory() {
      this.$refs['laboratoryForm'].validate((valid) => {
        if (valid) {
          const tempLaboratory = Object.assign({}, this.tempLaboratory)
          updateLaboratory(tempLaboratory).then(() => {
            this.fetchLaboratoryPage()
            this.dialogFormVisible = false
            showSuccessTip()
          })
        }
      })
    },
    handleDeleteLaboratory(id) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteLaboratory(id).then(() => {
          this.dialogFormVisible = false
          this.fetchLaboratoryPage()
          showSuccessTip()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
    // endregion
  }
}

</script>

<style lang="scss" scoped>
.muti-time-picker {
  display: flex;
}
</style>
